//
//  TYTimer.m
//  TYBase_Example
//
//  Created by 谢航宇 on 2023/7/7.
//  Copyright © 2023 谢航宇. All rights reserved.
//

#import "TYTimer.h"

@implementation TYTimer
+ (instancetype)timerInTarget:(id)obj step:(NSTimeInterval)step complete:(void(^)(NSTimeInterval second))timeAction {
    TYTimer * tyTimer = [[TYTimer alloc]init];
    tyTimer.step = step;
    tyTimer.obj = obj;
    tyTimer.timeAction = timeAction;
    return tyTimer;
}

- (void)setStep:(NSTimeInterval)step {
    _step = step;
    self.second -= step;
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        if (weakSelf.timer) {
            [weakSelf.timer invalidate];
            weakSelf.timer = nil;
        }
        NSLog(@"TYTimer-定时器刷新：开启");
        weakSelf.timer = [NSTimer timerWithTimeInterval:step target:weakSelf selector:@selector(timerFire:) userInfo:nil repeats:YES];
        [weakSelf.timer fire];
        [[NSRunLoop currentRunLoop]addTimer:weakSelf.timer forMode:NSRunLoopCommonModes];
        
    });
    
}

- (void)start {
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        if (weakSelf.timer) {
            [weakSelf.timer invalidate];
            weakSelf.timer = nil;
        }
        NSLog(@"TYTimer-定时器刷新：开启");
        weakSelf.timer = [NSTimer timerWithTimeInterval:weakSelf.step target:weakSelf selector:@selector(timerFire:) userInfo:nil repeats:YES];
        [weakSelf.timer fire];
        [[NSRunLoop currentRunLoop]addTimer:weakSelf.timer forMode:NSRunLoopCommonModes];
        
    });
    
}
- (void)stop {
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (void)timerFire:(NSTimer *)timer {
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        weakSelf.second += weakSelf.step;
        if (weakSelf.timeAction) {
            weakSelf.timeAction(weakSelf.second);
        }
        if (weakSelf.obj == nil) {
            [weakSelf.timer invalidate];
            weakSelf.timer = nil;
        }
        NSLog(@"TYTimer-定时器刷新：%f",weakSelf.second);
        
    });
}

- (void)dealloc {
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

@end
